package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"practice-hub/cache"
	"practice-hub/model"
	"practice-hub/pkg"
	"strconv"
	"time"
)

func DeliveryOrderDetail(c *gin.Context) {
	/*
		SELECT
		  deliveries.delivery_code DeliveryCode,
		  deliveries.delivery_name DeliveryName,
		  delivery_orders.order_code OrderCode,
		  delivery_orders.order_to OrderTo
		FROM
		  deliveries
		  LEFT JOIN delivery_orders ON deliveries.id = delivery_orders.did
	*/
	id, _ := strconv.Atoi(c.Query("id"))
	var list model.DeliveryOrderList
	redis_key := "delivery_order_detail_" + strconv.Itoa(int(id))
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("deliveries").
			Select(
				"deliveries.delivery_code DeliveryCode",
				"deliveries.delivery_name DeliveryName",
				"delivery_orders.order_code OrderCode",
				"delivery_orders.order_to OrderTo",
			).
			Joins("LEFT JOIN delivery_orders ON deliveries.id = delivery_orders.did").
			Where("delivery_orders.id=?", id).Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": list,
	})
	return
}
func DeliveryOrderList(c *gin.Context) {
	/*
		SELECT
		  deliveries.delivery_code DeliveryCode,
		  deliveries.delivery_name DeliveryName,
		  delivery_orders.order_code OrderCode,
		  delivery_orders.order_to OrderTo
		FROM
		  deliveries
		  LEFT JOIN delivery_orders ON deliveries.id = delivery_orders.did
	*/
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var total int64
	var list []model.DeliveryOrderList
	model.DB.Model(&model.DeliveryOrder{}).Count(&total)
	redis_key := "delivery_order_list_" + strconv.Itoa(int(page))
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("deliveries").
			Select(
				"deliveries.delivery_code DeliveryCode",
				"deliveries.delivery_name DeliveryName",
				"delivery_orders.order_code OrderCode",
				"delivery_orders.order_to OrderTo",
			).
			Joins("LEFT JOIN delivery_orders ON deliveries.id = delivery_orders.did").
			Offset(offset).Limit(size).Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  list,
		"total": total,
	})
	return
}
func RepoOrderDetail(c *gin.Context) {
	id, _ := strconv.Atoi(c.Query("id"))
	redis_key := "repo_order_detail_" + strconv.Itoa(id)
	var list model.RepoOrderList
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	/*
	   SELECT
	     repos.repo_code RepoCode,
	     repos.repo_name RepoName,
	     repo_orders.order_code OrderCode,
	     repo_orders.order_price OrderPrice
	   FROM
	     repos
	     LEFT JOIN repo_orders ON repos.id = repo_orders.rid
	*/
	if cacheData == "" {
		model.DB.Table("repos").
			Select(
				"repos.repo_code RepoCode",
				"repos.repo_name RepoName",
				"repo_orders.order_code OrderCode",
				"repo_orders.order_price OrderPrice",
			).
			Joins("LEFT JOIN repo_orders ON repos.id = repo_orders.rid").
			Where("repo_orders.id=?", id).Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": list,
	})
	return
}
func RepoOrderList(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var total int64
	model.DB.Model(&model.RepoOrder{}).Count(&total)
	redis_key := "repo_order_list_" + strconv.Itoa(page)
	var list []model.RepoOrderList
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	/*
	   SELECT
	     repos.repo_code RepoCode,
	     repos.repo_name RepoName,
	     repo_orders.order_code OrderCode,
	     repo_orders.order_price OrderPrice
	   FROM
	     repos
	     LEFT JOIN repo_orders ON repos.id = repo_orders.rid
	*/
	if cacheData == "" {
		model.DB.Table("repos").
			Select(
				"repos.repo_code RepoCode",
				"repos.repo_name RepoName",
				"repo_orders.order_code OrderCode",
				"repo_orders.order_price OrderPrice",
			).
			Joins("LEFT JOIN repo_orders ON repos.id = repo_orders.rid").
			Offset(offset).Limit(size).Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  list,
		"total": total,
	})
	return
}
func RepoOrderAdd(c *gin.Context) {
	order_code := c.PostForm("order_code")
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	order_price, _ := strconv.Atoi(c.PostForm("order_price"))
	data := model.RepoOrder{
		OrderCode:  order_code,
		Rid:        rid,
		OrderPrice: order_price,
	}
	if err := model.DB.Create(&data).Error; err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "订单添加失败",
		})
		return
	}
	redis_key := "repo_order_add_" + strconv.Itoa(int(data.ID))
	model.DB.Where("id=?", data.ID).Find(&model.RepoOrder{})
	jsonData, _ := json.Marshal(data)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "订单添加成功",
	})
	return
}
func RepoAdd(c *gin.Context) {
	repo_code := c.PostForm("repo_code")
	repo_name := c.PostForm("repo_name")
	if repo_code == "" || repo_name == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	data := model.Repo{
		RepoCode: repo_code,
		RepoName: repo_name,
	}
	if err := model.DB.Create(&data).Error; err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "仓库添加失败",
		})
		return
	}
	var list model.Repo
	redis_key := "repo_add_" + strconv.Itoa(int(data.ID))
	model.DB.Where("id=?", data.ID).Find(&list)
	jsonData, _ := json.Marshal(data)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "仓库添加成功",
	})
	return
}
func UserList(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	var list []model.User
	offset := (page - 1) * size
	var total int64
	model.DB.Model(&list).Count(&total)
	redis_key := "user_list_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Offset(offset).Limit(size).Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "权限查询成功",
		"data":  list,
		"total": total,
	})
	return
}
func RoleNode(c *gin.Context) {
	rid := c.Query("rid")
	/*
		SELECT
		  *
		FROM
		  nodes
		  LEFT JOIN role_nodes ON nodes.id = role_nodes.nid
		WHERE role_nodes.rid=1
	*/
	var node model.Node
	redis_key := "role_node_" + rid
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("nodes").
			Joins("LEFT JOIN role_nodes ON nodes.id = role_nodes.nid").
			Where("role_nodes.rid=?", rid).
			Find(&node)
		jsonData, _ := json.Marshal(node)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &node)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "权限查询成功",
		"data": node,
	})
	return
}
func UserRole(c *gin.Context) {
	uid := c.Query("uid")
	/*
		SELECT
		  *
		FROM
		  roles
		  LEFT JOIN user_roles ON roles.id = user_roles.rid
		WHERE user_roles.uid=1
	*/
	var role model.Role
	redis_key := "user_role_" + uid
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("roles").
			Joins("LEFT JOIN user_roles ON roles.id = user_roles.rid").
			Where("user_roles.uid=?", uid).
			Find(&role)
		jsonData, _ := json.Marshal(role)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &role)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "角色查询成功",
		"data": role,
	})
	return
}
func RoleNodeAdd(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	nid, _ := strconv.Atoi(c.PostForm("nid"))
	data := model.RoleNode{
		Rid: rid,
		Nid: nid,
	}
	if err := model.DB.Create(&data).Error; err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "角色与权限绑定失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "角色与权限绑定成功",
	})
	return
}
func UserRoleAdd(c *gin.Context) {
	uid, _ := strconv.Atoi(c.PostForm("uid"))
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	data := model.UserRole{
		Uid: uid,
		Rid: rid,
	}
	if err := model.DB.Create(&data).Error; err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户绑定角色失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "用户绑定角色成功",
	})
	return
}
func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	redis_key := "error_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "错误三次以上已禁封",
		})
		return
	}
	var user model.User
	if err := model.DB.Where("username=?", username).Find(&user).Error; err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}
	if user.Password != pkg.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "错误三次禁封两小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误重新输入",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登陆成功",
	})
	return
}
